// 工具函数

// 四舍五入取整
// @param {number} value: 要格式化的数字
// @param {number} n: 保留的小数位
// @return {number} 四舍五入后的结果
const round = (value, n) => {
    n = n === undefined ? 1 : n;
    let bei = Math.pow(10, n);
    let res = Math.round(value * bei) / bei;
    return +parseFloat(res.toPrecision(12));
};

// 默认绕原点旋转
// 在平面坐标上，任意点P(x1,y1)，绕一个坐标点Q(x2,y2)旋转θ角度后,新的坐标设为(x, y)的计算公式：
// x = (x1 - x2)*cos(θ) - (y1 - y2)*sin(θ) + x2 ;
// y = (x1 - x2)*sin(θ) + (y1 - y2)*cos(θ) + y2 ;
// @param {number} x1: 要旋转的点x坐标
// @param {number} y1: 要旋转的点x坐标
// @param {number} rotate: 旋转角度，顺时针旋转后的点坐标【注意是顺时针!!!】，单位是角度deg
// @param {number} x2: 围绕的点x坐标
// @param {number} y2: 围绕的点x坐标
// @return {x:number,y:number} 新的坐标点
const pointRotate = (x1, y1, rotate, x2 = 0, y2 = 0) => {
    // 弧度的计算公式为： 2*PI/360*角度；
    const θ = (-rotate * Math.PI) / 180;
    return {
        x: round((x1 - x2) * Math.cos(θ) - (y1 - y2) * Math.sin(θ) + x2, 2),
        y: round((x1 - x2) * Math.sin(θ) + (y1 - y2) * Math.cos(θ) + y2, 2),
    };
};

// 矩形旋转一定角度后，真实的宽高
// @param width: 矩形宽度
// @param height: 矩形高度
// @param rotate: 矩形旋转角度，单位是角度deg
// @return {width:number,height:number} 新的坐标点
const rectRealSize = (width = 0, height = 0, rotate = 0) => {
    const p1 = pointRotate(-width, height, rotate);
    const p2 = pointRotate(width, height, rotate);
    const p3 = pointRotate(width, -height, rotate);
    const p4 = pointRotate(-width, -height, rotate);

    const minX = Math.min(p1.x, p2.x, p3.x, p4.x);
    const minY = Math.min(p1.y, p2.y, p3.y, p4.y);

    const maxX = Math.max(p1.x, p2.x, p3.x, p4.x);
    const maxY = Math.max(p1.y, p2.y, p3.y, p4.y);

    return {
        width: 0.5 * (maxX - minX),
        height: 0.5 * (maxY - minY),
    };
};

// 获取矩形投影边缘距离
// 当rect2 的投影到 rect1 边缘时，rect1中心点与rect2中心点距离
// @param rect1: 矩形1
// @param rect1.x: 矩形1左上角x坐标
// @param rect1.y: 矩形1左上角y坐票
// @param rect1.w: 矩形1宽度
// @param rect1.h: 矩形1高度
// @param rect1.r: 矩形1围绕矩形中心点顺时针旋转的角度，单位是角度deg
// @param rect2: 矩形2
// @param rect2.x: 矩形2左上角x坐标
// @param rect2.y: 矩形2左上角y坐票
// @param rect2.w: 矩形2宽度
// @param rect2.h: 矩形2高度
// @param rect2.r: 矩形2围绕矩形中心点顺时针旋转的角度，单位是角度deg
const rectEdgeDistance = (
    rect1 = { x: 0, y: 0, w: 0, h: 0, r: 0 },
    rect2 = { x: 0, y: 0, w: 0, h: 0, r: 0 }
) => {
    // 中心点的距离与夹角
    const centerX = rect2.x + 0.5 * rect2.w - rect1.x - 0.5 * rect1.w;
    const centerY = rect2.y + 0.5 * rect2.h - rect1.y - 0.5 * rect1.h;
    // const centerR = (720 + Math.atan2(centerY, centerX) * 180 / Math.PI) % 360;
    const centerR = Math.atan2(centerY, centerX);

    const rotate = rect2.r - rect1.r;
    const p1 = pointRotate(
        centerX - 0.5 * rect2.w,
        centerY + 0.5 * rect2.h,
        rotate
    );
    const p2 = pointRotate(
        centerX + 0.5 * rect2.w,
        centerY + 0.5 * rect2.h,
        rotate
    );
    const p3 = pointRotate(
        centerX + 0.5 * rect2.w,
        centerY - 0.5 * rect2.h,
        rotate
    );
    const p4 = pointRotate(
        centerX - 0.5 * rect2.w,
        centerY - 0.5 * rect2.h,
        rotate
    );

    // 矩形1的角度
    // const deg = Math.atan2(rect1.h, rect1.w) * 180 / Math.PI;

    // let long = 0;
    // let distance = 0; // 中心点最小距离
    // let test = '';

    // if(Math.abs((centerR + 90) % 180 - 90) <= deg ){
    //     // x轴生效
    //     const minX = Math.min(p1.x,p2.x,p3.x,p4.x);
    //     const maxX = Math.max(p1.x,p2.x,p3.x,p4.x);
    //     long = 0.5 * rect1.w + 0.5*(maxX - minX);
    //     distance = Math.abs(long / Math.cos(centerR * Math.PI / 180));
    //     test = 'x轴'

    // }else{
    //     // y轴生效
    //     const minY = Math.min(p1.y,p2.y,p3.y,p4.y);
    //     const maxY = Math.max(p1.y,p2.y,p3.y,p4.y);
    //     long = 0.5 * rect1.h + 0.5*(maxY - minY);
    //     distance = Math.abs(long / Math.sin(centerR * Math.PI / 180));
    //     test = 'y轴'
    // }

    // x轴生效
    const sizeX =
        Math.max(p1.x, p2.x, p3.x, p4.x) - Math.min(p1.x, p2.x, p3.x, p4.x);
    const sizeY =
        Math.max(p1.y, p2.y, p3.y, p4.y) - Math.min(p1.y, p2.y, p3.y, p4.y);

    const longX = Math.abs((0.5 * rect1.w + 0.5 * sizeX) / Math.cos(centerR));
    const longY = Math.abs((0.5 * rect1.h + 0.5 * sizeY) / Math.sin(centerR));

    const testX = 0.5 * rect1.w + 0.5 * sizeX;
    const testY = 0.5 * rect1.h + 0.5 * sizeY;

    return { longX, longY, testX, testY };
};

// 判断矩形是否相交
// @param rect1: 矩形1
// @param rect1.x: 矩形1左上角x坐标
// @param rect1.y: 矩形1左上角y坐票
// @param rect1.w: 矩形1宽度
// @param rect1.h: 矩形1高度
// @param rect1.r: 矩形1围绕矩形中心点顺时针旋转的角度，单位是角度deg
// @param rect2: 矩形2
// @param rect2.x: 矩形2左上角x坐标
// @param rect2.y: 矩形2左上角y坐票
// @param rect2.w: 矩形2宽度
// @param rect2.h: 矩形2高度
// @param rect2.r: 矩形2围绕矩形中心点顺时针旋转的角度，单位是角度deg
const rectIsIntersect = (
    rect1 = { x: 0, y: 0, w: 0, h: 0, r: 0 },
    rect2 = { x: 0, y: 0, w: 0, h: 0, r: 0 }
) => {
    const centerX = rect2.x + 0.5 * rect2.w - rect1.x - 0.5 * rect1.w;
    const centerY = rect2.y + 0.5 * rect2.h - rect1.y - 0.5 * rect1.h;
    const centerR = Math.atan2(centerY, centerX);

    const distance1 = rectEdgeDistance(rect1, rect2);
    const distance2 = rectEdgeDistance(rect2, rect1);
    const distance = Math.min(
        distance1.longX,
        distance1.longY,
        distance2.longX,
        distance2.longY
    );

    // 优化点
    // 如果中点在容器内，则不管

    // 边界
    const edgeX = distance * Math.cos(centerR);
    const edgeY = distance * Math.sin(centerR);

    const resultX =
        centerX >= 0 ? Math.min(edgeX, centerX) : Math.max(edgeX, centerX);
    const resultY =
        centerY >= 0 ? Math.min(edgeY, centerY) : Math.max(edgeY, centerY);

    const result = {
        x: resultX + rect1.x + 0.5 * rect1.w - 0.5 * rect2.w,
        y: resultY + rect1.y + 0.5 * rect1.h - 0.5 * rect2.h,
    };

    return result;
};

const fiexImage = function (width, height, scale) {
    var s = scale || 1; // 宽高比例，高/宽
    var w = parseInt(width) || 1;
    var h = parseInt(height) || 1;
    if (h / w > s) {
        return {
            width: ((s * w) / h) * 100 + "%",
            height: "100%",
            left: (1 - (s * w) / h) * 50 + "%",
        };
    } else {
        return {
            width: "100%",
            height: (h / w / s) * 100 + "%",
            top: (1 - h / w / s) * 50 + "%",
        };
    }
};

// 获取有效的id值
const getUsableId = (piece) => {
    var id = 1;
    var layers = (piece || {}).layers || [];
    var ids = layers.map(function (i) {
        return i.id;
    });
    var res = [];
    var next = true;
    var count = 1;

    while (next) {
        ids.indexOf(id) < 0 && res.push(id);
        id = id + 1;
        next = res.length < count;
    }
    return res[0];
};

// 重置图片
const resetImage = (image, piece = {}, mapper = {}) => {
    // 图片放满屏幕,多出来的留白
    const offset = 0;
    const zoom = Math.max(
        piece.real_width / piece.canvas_width,
        piece.real_height / piece.canvas_height
    );
    const size = rectRealSize(
        piece.canvas_width,
        piece.canvas_height,
        piece.canvas_rotate
    );

    const width = size.width - offset;
    const height = size.height - offset;

    const scale = fiexImage(image.imageW, image.imageH, height / width);

    // 画布上最大的宽高
    const maxW = (parseFloat(scale.width) * width) / 100;
    const maxH = (parseFloat(scale.height) * height) / 100;

    // 是小dpi
    const minW = (image.imageW * 300) / 75 / zoom;
    const minH = (image.imageH * 300) / 75 / zoom;

    const realW = Math.min(maxW, minW);
    const realH = Math.min(maxH, minH);
    const realX = (piece.canvas_width - realW) / 2;
    const realY = (piece.canvas_height - realH) / 2;

    image.id = image.id || getUsableId(piece);
    image.type = "image"; // 类型[image|text]
    image.url = image.url;
    image.x = realX; // 图片最终显示x轴坐标
    image.y = realY; // 图片最终显示Y轴坐标
    image.w = realW; // 图片最终显示宽度
    image.h = realH; // 图片最终显示调试

    image.name = image.name;
    image.imageW = image.imageW; // 图片宽度
    image.imageH = image.imageH; // 图片高度

    image.cutW = image.imageW; // 图片裁剪宽度
    image.cutH = image.imageH; // 图片裁剪高度
    image.cutX = 0; // 图片裁剪左偏移
    image.cutY = 0; // 图片裁剪右偏移
    // image.rotate = -(mapper.rotate || piece.canvas_rotate || 0); // 旋转角度
    image.rotate = 0; // 旋转角度
    image.flipX = false; // 横向翻转
    image.flipY = false; // 竖向翻转
    image.tiled_type = ""; // 平铺方式[basic|mirror|brick|drop]
    image.tiled_hor = 0; // 平铺横向间距
    image.tiled_ver = 0; // 平铺横向间距

    return image;
};

const resetEmbPlaten = (platen, piece = {}, mapper = {}) => {
    platen.id = platen.id || getUsableId(piece);
    platen.type = "emg-platen"; // 类型[platen|text]
    platen.scale = piece.canvas_zoom; // 类型[platen|text]

    platen.w = platen.width * piece.canvas_zoom; // 图片最终显示宽度
    platen.h = platen.height * piece.canvas_zoom; // 图片最终显示调试
    platen.x = 0.5 * (piece.canvas_width - platen.w); // 图片最终显示x轴坐标
    platen.y = 0.5 * (piece.canvas_height - platen.h); // 图片最终显示Y轴坐标

    platen.name = platen.name;
    platen.width = platen.width; // 图片宽度
    platen.height = platen.height; // 图片高度
    platen.rotate = platen.rotate || 0; // 旋转角度
    platen.files = platen.files || [];
};

// 获取文字宽高
const getTextSize = (text, style) => {
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");

    const fontFamily = style.fontFamily || "Arial";
    const fontSize = style.fontSize || 12;
    const charSpacing = style.charSpacing || 0;

    ctx.font = fontSize + "px " + fontFamily;
    const size = ctx.measureText(text);
    const spacing = 0.75 * fontSize * charSpacing * Math.max(text.length, 0);

    return {
        width: size.width + spacing,
        height: fontSize,
    };
};

// 重置文字样式
const resetText = (text, piece, mapper) => {
    const style = {
        textAlign: "center",
        fontFamily: text.font_family || "Arial",
        fontSize: text.font_size || 100,
        lineHeight: text.font_size || 100,
        charSpacing: 0,
    };
    const size = getTextSize(text.text, style);

    text.w = size.width;
    text.h = size.height;
    text.x = ((piece || {}).canvas_width - text.w) / 2;
    text.y = ((piece || {}).canvas_height - text.h) / 2;

    text.id = text.id || getUsableId(piece);
    text.type = "text"; // 类型[image|text]
    text.text = text.text; // 文字内容
    text.font_size = style.fontSize; // 字号大小
    text.letter_spacing = style.charSpacing; // 字间距

    // text.rotate = -((mapper || {}).rotate || (piece || {}).canvas_rotate || 0); // 旋转角度
    text.rotate = 0; // 旋转角度
    text.flipX = false; // 横向翻转
    text.flipY = false; // 竖向翻转

    text.font_family = style.fontFamily; // 字体
    text.font_color = "#000"; // 颜色
    text.font_arc = 0; // 文字弧度

    text.outline_color = ""; // 外描边颜色
    text.outline_weight = 0.1; // 外描边大小，字号大小百分比
    text.outline_offset = 0; // 外描边与文字距离，字号大小百分比
    text.shadow_color = ""; // 阴影颜色
    text.shadow_blur = 0; // 模糊距离
    text.shadow_distance = 0.1; // 阴影宽度，字号大小百分比
    text.shadow_angle = 0; // 阴影角度
    text.tiled_type = ""; // 平铺方式[basic|mirror|brick|drop]
    text.tiled_hor = 0; // 平铺横向间距
    text.tiled_ver = 0; // 平铺横向间距

    return text;
};

const colorRgb = (color) => {
    var sColor = color.toLowerCase();
    //十六进制颜色值的正则表达式
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    // 如果是16进制颜色
    if (sColor && reg.test(sColor)) {
        if (sColor.length === 4) {
            var sColorNew = "#";
            for (var i = 1; i < 4; i += 1) {
                sColorNew += sColor
                    .slice(i, i + 1)
                    .concat(sColor.slice(i, i + 1));
            }
            sColor = sColorNew;
        }
        //处理六位的颜色值
        var sColorChange = [];
        for (var i = 1; i < 7; i += 2) {
            sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
        }
        return sColorChange;
    }
};

export const getEmbPrice = (count, platen) => {
    // https://podpartner.feishu.cn/wiki/P6iawotHpiwyYMkHN4vcsfEmnMb
    // 1000 针 0.3 美元

    if (!count || count == 0) {
        return 0;
    } else {
        const format = Object.assign({}, platen);
        const base_price = format.base_price || 0;
        const base_stitches = format.base_stitches || 0;
        const append =
            Math.ceil(Math.max(0, count - base_stitches) / 1000) * 30;
        return base_price + append;
    }
};

// 坐标旋转
// x,y 点的坐标
// xo,yo 镜像原点
// r 旋转角度
const coordinateRotation = (x, y, ox, oy, r) => {
    const radians = (-r * Math.PI) / 180;
    const cos = Math.cos(radians);
    const sin = Math.sin(radians);

    const x1 = x - ox;
    const y1 = y - oy;
    const xr = x1 * cos + y1 * sin;
    const yr = y1 * cos - x1 * sin;

    return {
        x: xr + ox,
        y: yr + oy,
    };
};

export const Base64 = {
    // private property
    _keyStr:
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output =
                output +
                Base64._keyStr.charAt(enc1) +
                Base64._keyStr.charAt(enc2) +
                Base64._keyStr.charAt(enc3) +
                Base64._keyStr.charAt(enc4);
        }

        return output;
    },

    // public method for decoding
    decode: function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {
            enc1 = Base64._keyStr.indexOf(input.charAt(i++));
            enc2 = Base64._keyStr.indexOf(input.charAt(i++));
            enc3 = Base64._keyStr.indexOf(input.charAt(i++));
            enc4 = Base64._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }

        output = Base64._utf8_decode(output);

        return output;
    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if (c > 127 && c < 2048) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = (c1 = c2 = 0);

        while (i < utftext.length) {
            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if (c > 191 && c < 224) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(
                    ((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
                );
                i += 3;
            }
        }
        return string;
    },
};

export default {
    round,
    pointRotate,
    rectRealSize,
    rectIsIntersect,
    resetImage,
    resetText,
    resetEmbPlaten,
    getTextSize,
    getUsableId,
    colorRgb,
    getEmbPrice,
    coordinateRotation,
};
